<template>
    <div class="vue-echarts" :id="id" :style="style">
    </div>
</template>

<script>
    import echarts from 'echarts';
    export default {
        name: 'vue-echarts',
        data: function () {
            return {
                loadJS: '', // 存储异步加载echart的promise状态
                chart: '',
                arr: [{"name": "鄂尔多斯", "value": 12},{"name": "鄂尔多斯", "value": 12},{"name": "鄂尔多斯", "value": 12},{"name": "鄂尔多斯", "value": 12}]// 保存地图初始化的实例
            }
        },
        props: {
            id: {
                type: String,
                default: function () { // 生成一个随机字符串,纯英文的,当不传入ID的时候生成实例,加i确保不会随机到一样的
                    let temp = [];
                    for (let i = 0; i < 6; i++) {
                        let randomChar = String.fromCharCode(65 + Math.floor(Math.random() * 19) + i);
                        temp.push(randomChar);

                    }
                    return temp.reduce((pre, next) => pre + next);
                }
            },
            height: { // 图表高度
                type: String,
                default: '300px'
            },
            width: { // 图表宽度
                type: String,
                default: '100%'
            },
            legend: { // 以下的配置都是echarts官方图表的自定义部分,我拆分这么几大块
                type: Object,
                default: function () {
                    return {
                        data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
                    }
                }
            },
            title: {
                type: Object,
                default: function () {
                    return {
                        text: '堆叠区域图'
                    }
                }
            },
            tooltip: {
                type: [Array, Object],
                default: function () {
                    return {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                            label: {
                                backgroundColor: '#6a7985'
                            },
                            animation: true
                        }
                    }
                }
            },
            toolbox: {
                type: Object,
                default: function () {
                    return {
                        show: true,
                        feature: {
                            dataZoom: {
                                yAxisIndex: 'none'
                            },
                            dataView: { readOnly: false },
                            magicType: { type: ['line', 'bar'] },
                            restore: {},
                            saveAsImage: {}
                        }
                    }
                }
            },
            grid: {
                type: Object,
                default: function () {
                    return {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    }
                }
            },
            xAxis: {
                type: [Array, Object],
                default: function () {
                    return [
                        {
                            type: 'category',
                            boundaryGap: true,
                            data: ['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00', '24:00']

                        }
                    ]
                }
            },
            yAxis: {
                type: [Array, Object],
                default: function () {
                    return [
                        {
                            type: 'value'
                        }
                    ]
                }
            },
            series: {
                /*type: [Array, Object],*/
                type: [Array,Array],
                /*type: 'json',*/
                default: function () {

                    return [

                        {
                            name: (function(){
                               let nam = ['曝光'];
                               let arr=[];
                               for(let i = 0; i < nam.length; i++)
                                   arr = nam[i];
                                return arr;
                            })(),
                            markPoint: {
                                data: [
                                    {
                                        name: '某个坐标',
                                        coord: [1, 0],
                                    },
                                    {
                                        name: '某个坐标',
                                        coord: [2, 0],
                                    },
                                    {
                                        name: '某个坐标',
                                        coord: [3, 0],
                                    },
                                    {
                                        name: '某个坐标',
                                        coord: [4, 0],
                                    },
                                    {
                                        name: '某个坐标',
                                        coord: [5, 0],
                                    },
                                    {
                                        name: '某个坐标',
                                        coord: [6, 0],
                                    }
                                ]
                            },
                            label: {normal: {
                                show: true
                            }},
                            type: 'line',
                            smooth: true,
                            lineStyle: {
                                normal: {
                                    color: '#f00',
                                }
                            },
                            data: [120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90, 120]
                            /*(function (arr) {
                                let res = []
                                for(let i = 0; i < arr.length; i++){
                                    res.push(arr[i].value)
                                }
                                return res;
                            })()*/
                            /*data: (function (arr) {
                                return arr.value;
                            })()*/
                        },
                        {
                            name: '点击',
                            type: 'line',
                            smooth: true,
                            lineStyle: {
                                normal: {
                                    color: '#20a0ff',
                                }
                            },
                            data: [220, 182, 191, 234, 290, 330, 310, 120, 132, 101, 134, 90, 120]
                        },
                        {
                            name: '点击率',
                            type: 'line',
                            lineStyle: {
                                normal: {
                                    color: '#42b983',
                                }
                            },
                            smooth: true,
                            data: [150, 232, 201, 154, 190, 330, 410, 120, 132, 101, 134, 90, 120]
                        }
                    ]
                }
            },
            setOption: {
                type: Object,
                default: function () {
                    return null;
                }
            }

        },
        computed: {
            style () {
                return {
                    height: this.height,
                    width: this.width
                }
            },
            setOptions () { // 若是外部传入options则用外部的,否则就是拼凑的options
                if (this.setOption) {
                    return this.setOption;
                } else {
                    return {
                        title: this.title,
                        tooltip: this.tooltip,
                        legend: this.legend,
                        toolbox: this.toolbox,
                        grid: this.grid,
                        xAxis: this.xAxis,
                        yAxis: this.yAxis,
                        series: this.series
                    }
                }
            }
        },
        created () {

            if (this.loadJS === '' && !document.getElementById('cdnEchart')) {
                this.loadJS = this.loadEchartsJS();
            } else {
                this.$nextTick(() => {
                    this.init();
                })
            }
        },
        mounted () {
            if (document.getElementById('cdnEchart')) {
                this.loadJS.then(() => {
                    this.init(); // CDNJS加载后,元素渲染后,初始化图表
                }).catch(err => {
                    console.log('echarts js加载失败');
                });
            }
        },
        beforeDestroy () {
            window.removeEventListener('resize', this.chart.resize)
            if (this.char) {
                this.chart.dispose(); // 销毁图表实例
            }
        },
        methods: {
            init () { // 初始化图表
                this.chart = new echarts.init(document.getElementById(this.id));
                this.chart.setOption(this.setOptions);
                window.addEventListener('resize', this.chart.resize) // 图表响应大小的关键,重绘
            },
            loadEchartsJS () { // 异步请求cdnjs
                const CDNURL = '//cdn.bootcss.com/echarts/3.6.2/echarts.common.min.js';
                return new Promise((resolve, reject) => {
                    const script = document.createElement('script');
                    script.type = "text/javascript";
                    script.id = "cdnEchart";
                    if (script.readyState) {  //IE
                        script.onreadystatechange = function () {
                            if (script.readyState == "loaded" ||
                                script.readyState == "complete") {
                                script.onreadystatechange = null;
                                resolve('success: ' + CDNURL);
                            }
                        };
                    } else {  //Others
                        script.onload = function () {
                            resolve('success: ' + CDNURL);
                        };
                    }
                    script.onerror = function () {
                        reject(Error(CDNURL + 'load error!'));
                    };
                    script.src = CDNURL;
                    document.head.appendChild(script);
                });
            }
        },
        watch: {
            'setOption' (newVal) { // 监听外部传入的值,渲染新的的图表数据
                this.chart.setOption(newVal);
                this.chart.resize();
            }
        }
    }
</script>
